package com.ilink.teacherservice.service.impl.xiaolian;

import com.aliyun.bailian20231229.models.ListIndicesResponse;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.ilink.ilinkcommon.config.BailianConfigNew;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.teacherservice.service.bailian.ListIndicesService;
import com.ilink.teacherservice.service.impl.bailian.RetrieveServiceImpl;
import com.ilink.teacherservice.service.xiaolian.XiaolianRetrieveService;
import com.ilink.teacherservice.utils.bailian.BailianFileTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional
public class XiaolianRetrieveServiceImpl implements XiaolianRetrieveService {
    @Autowired
    ListIndicesService listIndicesService;
    @Autowired
    RetrieveServiceImpl retrieveService;
    @Override
    public RetrieveResponse Retrieve(String query,String indexName) throws Exception {
        com.aliyun.bailian20231229.Client client = BailianConfigNew.createBailianClient();
        // 知识库索引名称
        ListIndicesResponse listIndicesResponse = listIndicesService.listIndices(client, indexName, BailianConfigNew.workspaceId);

        if (!BailianFileTools.checkResponse(listIndicesResponse)) {
            log.error("获取索引列表失败: {}", listIndicesResponse.getBody().getMessage());
            throw new Exception("未找到对应的索引ID");
        }
        // 获取对应知识库索引ID
        String indexId = BailianFileTools.getIndexIdByName(listIndicesResponse, indexName);

        // 在指定知识库索引检索
        RetrieveResponse retrieve = retrieveService.retrieve(client, query, indexId, BailianConfigNew.workspaceId);
        if (!BailianFileTools.checkResponse(retrieve)) {
            log.error("检索接口调用失败: {}", retrieve.getBody().getMessage());
            throw new Exception("检索接口调用失败: " + retrieve.getBody().getMessage());
        }
        return retrieve;
    }

}
